package logic

import (
	"cart/cart"
	"cart/internal/svc"
	"cart/models/mysql"
	"cart/models/redis"
	"context"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	g := mysql.Goods{}
	err := g.GoodsFind(int(in.GoodsId))
	if err != nil {
		logx.Errorf("商品不存在")
		return nil, err
	}
	if g.ID == 0 {
		logx.Errorf("商品不存在")
		return nil, err
	}
	if g.Stock < int(in.Num) {
		logx.Errorf("商品库存不足")
		return nil, err
	}

	err = redis.CartAdd(int(in.UserId), int(in.GoodsId), int(in.Num))
	if err != nil {
		return nil, err
	}

	return &cart.CartAddResponse{GoodsId: in.GoodsId}, nil
}
